package com.yune.activity.main.ui.playing;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.snackbar.Snackbar;
import com.yune.R;
import com.yune.activity.App;
import com.yune.activity.main.MainActivity;
import com.yune.activity.playlist.PlayListActivity;
import com.yune.adapter.SongListAdapter;
import com.yune.bean.LrcBean;
import com.yune.bean.SongBean;
import com.yune.utils.DownloadUtil;
import com.yune.utils.NetWorkCallback;
import com.yune.utils.Network;
import com.yune.utils.Utils;
import com.yune.view.LrcView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class PlayingFragment extends Fragment {
    private ImageView playerController,midPicture;
    private SeekBar seek;
    private TextView time_now,time_all;
    private ViewPager vp;
    private View root,player,lyric;
    private LrcView mLrcView;
    private boolean isPlaying=false;
    private LinearLayout backgrounder;
    private boolean mode_single_loop=false;
    private ImageView play_modecontroller;
    private ObjectAnimator anim;
    private SeekBar volumeSeek;
    private AudioManager am;
    private SongBean songMsg;
    private ImageView like;
    private boolean isInitLike=false;
    private PopupWindow findPop;
    private ArrayList<SongBean> lyc_listdata;
    private SongListAdapter songListAdapter;
    private TextView findlyc_pop_title;

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (root==null) {
            root = inflater.inflate(R.layout.frgament_playing, container, false);
            //这个界面我做成了viewpaper，一个是播放界面，左滑是歌词界面,
            initvp();//初始化viewpaper
            //初始化vp之后初始化player和lyric两个页面的时候，里面就不能用root根节点，而要用vp初始化出来的player和lyric
            initplayer();
            initLyric();
            initFindLrPop();
            //初始化音量控制
            initVolume();
            //全部初始化完毕开始执行
            exe();
        }
        return root;
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
//初始化广播接收者,主要监听服务给我们返回了些啥
        initBroadcast();
    }

    @SuppressLint("InflateParams")
    private void initvp() {
        vp=root.findViewById(R.id.vp);
        LayoutInflater inflater2=getLayoutInflater();
        player = inflater2.inflate(R.layout.frgament_playing_player, null);
        lyric = inflater2.inflate(R.layout.frgament_playing_lyric,null);
        ArrayList<View> viewList = new ArrayList<>();// 将要分页显示的View装入数组中
        viewList.add(player);
        viewList.add(lyric);
        vp.setAdapter(new PagerAdapter() {
            @Override
            public boolean isViewFromObject(@NonNull View arg0, @NonNull Object arg1) { return arg0 == arg1; }
            @Override
            public int getCount() {
                return viewList.size();
            }
            @Override
            public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(viewList.get(position)); }
            @NonNull
            @Override
            public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(viewList.get(position));return viewList.get(position); }
        });
    }
    @SuppressLint("ClickableViewAccessibility")
    private void initFindLrPop() {
        @SuppressLint("InflateParams") View v = LayoutInflater.from(getContext()).inflate(R.layout.frgament_find_lyric_pop, null);
        findPop = new PopupWindow(v, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
        findPop.setFocusable(true);
        findPop.setTouchable(true);
        findPop.setOnDismissListener(() -> Utils.backgroundAlpha(1f,requireActivity()));
        findPop.setTouchInterceptor((v1, event) -> false);
        ListView find_pop_lv = v.findViewById(R.id.findlyc_pop_list);
        lyc_listdata=new ArrayList<>();
        songListAdapter=new SongListAdapter(requireActivity(),lyc_listdata);
        find_pop_lv.setAdapter(songListAdapter);
        find_pop_lv.setOnItemClickListener((parent, view, position, id) -> {
            SongBean bean = lyc_listdata.get(position);
            Network.callApi("https://autumnfish.cn/lyric?id=" + bean.songId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) { }
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        JSONObject jsonObject=new JSONObject(response.body().string());
                        if (!jsonObject.isNull("lrc")){
                            String str = jsonObject.getJSONObject("lrc").getString("lyric");
                            mLrcView.setLrcData(Utils.getLycData(str));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
            findPop.dismiss();
            Utils.backgroundAlpha(1,requireActivity());
        });
        findPop.setOnDismissListener(() -> Utils.backgroundAlpha(1f,requireActivity()));
        findlyc_pop_title=v.findViewById(R.id.findlyc_pop_title);
        findlyc_pop_title.setOnClickListener(v12 -> {
            EditText et=new EditText(getContext());
            et.setHint("请输入歌名");
            et.setText(findlyc_pop_title.getText().toString());
            AlertDialog.Builder dialog=new AlertDialog.Builder(getContext());
            dialog.setTitle("更改歌曲名字");
            dialog.setView(et);
            dialog.setPositiveButton("确定", (dialog1, which) -> {
                String str=et.getText().toString();
                if (!str.equals("")){
                    findlyc_pop_title.setText(str);
                    Network.callApi("https://autumnfish.cn/cloudsearch?keywords=" + URLEncoder.encode(str), new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) {
                            requireActivity().runOnUiThread(() -> {
                                try{
                                    JSONArray jsonArray=new JSONObject(response.body().string()).getJSONObject("result").getJSONArray("songs");
                                    songListAdapter.clear();
                                    for (int j= 0;j<jsonArray.length();j++){
                                        JSONObject jsonObject1= (JSONObject) jsonArray.get(j);
                                        SongBean adpFindBean =new SongBean(jsonObject1.getString("name"),
                                                jsonObject1.getJSONArray("ar").getJSONObject(0).getString("name"),
                                                jsonObject1.getJSONObject("al").getString("picUrl"),
                                                jsonObject1.getString("id"),
                                                "",
                                                true,
                                                "");
                                        lyc_listdata.add(adpFindBean);
                                    }
                                    songListAdapter.notifyDataSetChanged();
                                }catch (Exception e){
                                    e.printStackTrace();
                                }
                            });
                        }
                    });
                }
            }).setNegativeButton("取消",null).show();
        });
    }
    @SuppressLint("SetTextI18n")
    private void initLyric() {
        mLrcView = lyric.findViewById(R.id.lrc_view);
        mLrcView.setOnPlayIndicatorLineListener((time, content) -> {
            Intent intent = new Intent();
            intent.setAction("serviceReceiver");
            intent.putExtra("cmd","seekTo");
            intent.putExtra("progress",time);
            requireContext().sendBroadcast(intent);
        });
        lyric.findViewById(R.id.lyric_bottom).setOnClickListener(v -> {
            File file=new File(songMsg.songName);
            String name=file.getName().replaceAll("[.][^.]+$", "");
            findlyc_pop_title.setText("找歌词:"+name);
            findPop.showAtLocation(root, ViewGroup.LayoutParams.MATCH_PARENT ,0,500);
            Utils.backgroundAlpha(0.5f,requireActivity());
            Network.callApi("https://autumnfish.cn/cloudsearch?keywords=" + URLEncoder.encode(name), new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    requireActivity().runOnUiThread(() -> Toast.makeText(requireActivity(),"查询无结果",Toast.LENGTH_SHORT).show());
                }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                   requireActivity().runOnUiThread(() -> {
                       try {
                           JSONArray jsonArray=new JSONObject(response.body().string()).getJSONObject("result").getJSONArray("songs");
                           songListAdapter.clear();
                           for (int j= 0;j<jsonArray.length();j++){
                               JSONObject jsonObject1= (JSONObject) jsonArray.get(j);
                               SongBean adpFindBean =new SongBean(jsonObject1.getString("name"),
                                       jsonObject1.getJSONArray("ar").getJSONObject(0).getString("name"),
                                       jsonObject1.getJSONObject("al").getString("picUrl"),
                                       jsonObject1.getString("id"),
                                       "",
                                       true,
                                       "");
                               lyc_listdata.add(adpFindBean);
                           }
                           songListAdapter.notifyDataSetChanged();
                       } catch (Exception e) {
                           e.printStackTrace();
                       }
                       songListAdapter.notifyDataSetChanged();
                   });
                }
            });
        });
    }
    private void exe() {
        if (getArguments()!=null &&getArguments().getString("loadFile")!=null) {
            String path = getArguments().getString("loadFile");
            Intent intent1 = new Intent();
            intent1.putExtra("cmd","newPlay");
            intent1.setAction("serviceReceiver");
            intent1.putExtra("songUrl",path);
            intent1.putExtra("songName",new File(path).getName());
            intent1.putExtra("singer","未知歌手");
            intent1.putExtra("picture","http://p3.music.126.net/92WxKsTbOeYkNB8PuA2nOg==/109951165647810950.jpg?param=200y200");
            intent1.putExtra("songId",String.valueOf(System.currentTimeMillis()));
            intent1.putExtra("fromWeb",false);
            requireContext().sendBroadcast(intent1);
        }else{
            requireContext().sendBroadcast(new Intent().setAction("serviceReceiver").putExtra("cmd","getPlayStatus"));
        }
    }
    private void initBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("musicFrgamentReceiver");
        requireActivity().registerReceiver(new BroadcastReceiver() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onReceive(Context context, Intent intent) {
                String cmd=intent.getStringExtra("cmd");
                if (cmd.equals("backStatus")){
                    songMsg=new SongBean(intent.getStringExtra("songName"), intent.getStringExtra("singer"), intent.getStringExtra("picture"), intent.getStringExtra("songId"), intent.getStringExtra("songUrl"), intent.getBooleanExtra("fromWeb",false),intent.getStringExtra("ifAddedOid"));
//                    Objects.requireNonNull(((MainActivity) requireActivity()).getSupportActionBar()).setTitle(songMsg.songName);
                    //在播放就初始化进度啥的，点击下一首也要返回这个backStatus
                    if (intent.getBooleanExtra("fromWeb",false)){
                        //获取歌词
                        Network.callApi("https://autumnfish.cn/lyric?id=" + intent.getStringExtra("songId"), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                                try {
                                    assert response.body() != null;
                                    JSONObject jsonObject=new JSONObject(response.body().string());
                                    if (!jsonObject.isNull("lrc")){
                                        String str = jsonObject.getJSONObject("lrc").getString("lyric");
                                        mLrcView.setLrcData(Utils.getLycData(str));
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }else{
                        List<LrcBean> lrclist=new ArrayList<>();
                        lrclist.add(new LrcBean(0,"本地歌曲请手动获取歌词~"));
                        mLrcView.setLrcData(lrclist);
                    }
                    //获取图片
                    String pic=intent.getStringExtra("picture");
                    if (pic!=null){Utils.loadPic(pic,midPicture,backgrounder);}
                    if (intent.getBooleanExtra("isPlaying",false)){
                        anim.start();
                        playerController.setImageResource(R.drawable.pause);
                        int all=intent.getIntExtra("duration",0);
                        seek.setMax(all);
                        time_all.setText(Utils.calculateTime(all/1000));
                        isPlaying=true;
                    }else {
                        isPlaying=false;
                        anim.pause();
                        playerController.setImageResource(R.drawable.play);
                    }
                    if (!isInitLike){
                        try {
                            JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg",""));
                            String userObjectId=loginMsg.getString("objectId");
                            String songObjectId=songMsg.songId;
                            String url="https://api2.bmob.cn/1/classes/playList?where=" + URLEncoder.encode("{\"userObjectId\":\""+userObjectId+"\",\"songObjectId\":\""+songObjectId+"\"}");
                            Network.get(url, res -> {
                                JSONArray result = new JSONObject(res).getJSONArray("results");
                                if (result.length()==0){
                                    like.setImageResource(R.drawable.like);
                                }else {
                                    like.setImageResource(R.drawable.liked);
                                }
                            });

                        } catch (JSONException ignored) {}
                        isInitLike=true;
                    }
                }
                if (cmd.equals("playingProgress")){
                    int now=intent.getIntExtra("progress",-1);
                    seek.setProgress(now);
                    time_now.setText(Utils.calculateTime(now/1000));
                    mLrcView.updateTime(now);
                }
            }
        }, intentFilter);
    }
    @SuppressLint("WrongConstant")
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void initplayer() {
        playerController=player.findViewById(R.id.music_playController);
        midPicture=player.findViewById(R.id.music_midPicture);
        backgrounder =player.findViewById(R.id.music_backgroung);
        seek=player.findViewById(R.id.music_seek);
        time_now=player.findViewById(R.id.music_time_now);
        time_all=player.findViewById(R.id.music_time_all);
        play_modecontroller=player.findViewById(R.id.music_play_modecontroller);
        LinearLayout lastsong = player.findViewById(R.id.music_lastsong);
        LinearLayout nextsong = player.findViewById(R.id.music_nextsong);
        player.findViewById(R.id.music_share).setOnClickListener((v)->{
            Intent intent = new Intent("android.intent.action.SEND");
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, "分享");
            intent.putExtra(Intent.EXTRA_TEXT, "我正在 余音 听"+songMsg.singer+"的"+songMsg.songName+",你也来听听吧！\n地址:"+songMsg.songUrl);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            requireContext().startActivity(intent);
        });
        playerController.setOnClickListener((v)->{
            Intent intent = new Intent();
            intent.setAction("serviceReceiver");
            if (isPlaying){
                anim.pause();
                intent.putExtra("cmd","pause");
            }else {
                anim.start();
                intent.putExtra("cmd","play");
            }
            requireContext().sendBroadcast(intent);
        });
        seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser){
                    Intent intent = new Intent();
                    intent.setAction("serviceReceiver");
                    intent.putExtra("cmd","seekTo");
                    intent.putExtra("progress",progress);
                    requireContext().sendBroadcast(intent);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        player.findViewById(R.id.music_switchToLrc).setOnClickListener((v)-> vp.setCurrentItem(1));
        player.findViewById(R.id.music_play_mode).setOnClickListener(v -> {
            if (mode_single_loop){
                mode_single_loop=false;
                Snackbar.make(root,"列表循环",Snackbar.LENGTH_SHORT).show();
                play_modecontroller.setImageResource(R.drawable.recycle);
                Intent intent = new Intent();
                intent.setAction("serviceReceiver");
                intent.putExtra("cmd","not_single_loop");
                requireContext().sendBroadcast(intent);
            }else{
                mode_single_loop=true;
                Snackbar.make(root,"单曲循环",Snackbar.LENGTH_SHORT).show();
                play_modecontroller.setImageResource(R.drawable.singlerecycle);
                Intent intent = new Intent();
                intent.setAction("serviceReceiver");
                intent.putExtra("cmd","single_loop");
                requireContext().sendBroadcast(intent);
            }
        });
        like=player.findViewById(R.id.music_like);
        player.findViewById(R.id.music_like_btn).setOnClickListener(v -> {
            if (songMsg!=null&&songMsg.fromWeb){
                try {
                    JSONObject loginMsg=new JSONObject(App.sp.getString("loginMsg",""));
                    String userObjectId=loginMsg.getString("objectId");
                    String songObjectId=songMsg.ifAddedOid;
                    String url="https://api2.bmob.cn/1/classes/playList?where=" + URLEncoder.encode("{\"userObjectId\":\""+userObjectId+"\",\"songObjectId\":\""+songObjectId+"\"}");
                    Network.get(url, res -> {
                        JSONObject result = new JSONObject(res);
                        if (result.isNull("error")){//有表
                            JSONArray results=result.getJSONArray("results");
                            if (results.length()==0){
                                JSONObject jo=new JSONObject();
                                jo.put("songObjectId",songMsg.ifAddedOid);
                                jo.put("userObjectId",loginMsg.getString("objectId"));
                                Network.post(jo, "https://api2.bmob.cn/1/classes/playList",null);
                                requireActivity().runOnUiThread(() -> {
                                    like.setImageResource(R.drawable.liked);
                                    Toast.makeText(requireContext(), "已添加", Toast.LENGTH_SHORT).show();
                                });
                            }else{
                                for (int i = 0; i < results.length(); i++) {
                                    Network.delete("https://api2.bmob.cn/1/classes/playList/"+results.getJSONObject(i).getString("objectId"),null);
                                }
                                requireActivity().runOnUiThread(() -> {
                                    like.setImageResource(R.drawable.like);
                                    Toast.makeText(requireContext(), "已移除", Toast.LENGTH_SHORT).show();
                                });
                            }
                        }else{//没有表直接创建
                            JSONObject jo=new JSONObject();
                            jo.put("songObjectId",songMsg.ifAddedOid);
                            jo.put("userObjectId",loginMsg.getString("objectId"));
                            Network.post(jo, "https://api2.bmob.cn/1/classes/playList",null);
                            requireActivity().runOnUiThread(() -> {
                                like.setImageResource(R.drawable.liked);
                                Toast.makeText(requireContext(), "已添加", Toast.LENGTH_SHORT).show();
                            });
                        }
                    });
                } catch (JSONException ignored) {}
            }else{
                Toast.makeText(requireContext(), "本地歌曲不支持加入播放列表", Toast.LENGTH_SHORT).show();
            }
        });
        player.findViewById(R.id.music_showplayList).setOnClickListener((v)-> requireActivity().startActivity(new Intent(requireContext(), PlayListActivity.class)));
        lastsong.setOnClickListener((v)->{
            Intent intent=new Intent();
            intent.setAction("serviceReceiver");
            intent.putExtra("cmd","lastsong");
            requireActivity().sendBroadcast(intent);
        });
        nextsong.setOnClickListener((v)->{
            Intent intent=new Intent();
            intent.setAction("serviceReceiver");
            intent.putExtra("cmd","nextsong");
            requireActivity().sendBroadcast(intent);
        });
        player.findViewById(R.id.music_download).setOnClickListener((v)->{
            if (songMsg!=null){//是网络文件才可下载
                Snackbar.make(root,"开始下载",Snackbar.LENGTH_SHORT).show();
                DownloadUtil.get().download(getContext(), songMsg.songUrl,"/余音/",songMsg.songName+"-"+songMsg.singer+".mp3",  new DownloadUtil.OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(File file) {
                        Snackbar.make(root,"下载完毕",Snackbar.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onDownloading(int progress) {
                    }
                    @Override
                    public void onDownloadFailed() {
                        Snackbar.make(root,"下载失败",Snackbar.LENGTH_SHORT).show();
                    }
                });
            }
        });
        anim = ObjectAnimator.ofFloat(midPicture, "rotation", 0f, 360f);
        anim.setDuration(30000);
        anim.setInterpolator(new LinearInterpolator());
        anim.setRepeatMode(Animation.RESTART);
        anim.setRepeatCount(-1);
        AnimatorListener listener = new AnimatorListener(anim);
        anim.addUpdateListener(listener);
        anim.start();
    }
    private void initVolume() {
        volumeSeek=player.findViewById(R.id.music_volume_seek);
        am = (AudioManager)requireContext().getSystemService(Context.AUDIO_SERVICE);
        //获取系统最大音量
        volumeSeek.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        //获取当前音量
        volumeSeek.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));
        volumeSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if(fromUser){
                    //设置系统音量
                    am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
                    int currentVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
                    seekBar.setProgress(currentVolume);
                }
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) { }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) { }
        });
        VolumeReceiver volumeReceiver = new VolumeReceiver();
        IntentFilter filter = new IntentFilter() ;
        filter.addAction("android.media.VOLUME_CHANGED_ACTION") ;
        requireContext().registerReceiver(volumeReceiver, filter) ;
    }
    private class VolumeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")){
                volumeSeek.setProgress(am.getStreamVolume(AudioManager.STREAM_MUSIC));
            }
        }
    }
}